package com.tinyideatech.wechat.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tinyideatech.common.core.controller.BaseController;
import com.tinyideatech.common.core.entity.ApiResult;
import com.tinyideatech.framework.dto.FTP;
import com.tinyideatech.framework.service.QrcodeService;
import com.tinyideatech.framework.utils.FtpUtil;
import com.tinyideatech.system.entity.CarDevice;
import com.tinyideatech.system.service.ICarDeviceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

@RestController
@RequestMapping("/ws/v2/api/qrcode")
@Api("商城二维码接口")
public class QrcodeController extends BaseController {

    @Value("${tinyideatech.host}")
    private String host;

    @Value("${tinyideatech.profile}")
    private String profile;

    @Autowired
    private FTP ftpCatalog;

    private static final String remoteDir = "/qrcode";

    @Autowired
    private ICarDeviceService deviceService;

    /**
     * 车机请求服务器生成商城网址二维码
     * /api/qrcode/create/ + 车机ID
     *
     * @param id
     * @return
     */
    @ApiOperation("商城创建访问二维码图片接口")
    @GetMapping("/create/{id}")
    public ApiResult qrcode(@PathVariable("id") String id) {
        List<CarDevice> deviceList = deviceService.list(new QueryWrapper<CarDevice>().eq("device_id", id));
        if (deviceList.size() < 1) {
            // 2019-11-14 添加商城增添设备
            CarDevice carDevice = new CarDevice();
            carDevice.setDeviceId(id);
            carDevice.setDeviceProperties("新增");
            deviceService.save(carDevice);
        }
        String format = "png";
        String text = host + "wx/index?deviceId=" + id;
        int width = 250;
        int height = 250;
        try {
            ByteArrayOutputStream baos = QrcodeService.generateQRCode(text, width, height, format);
            final ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
            FtpUtil.uploadFileToFtp(ftpCatalog.getFTPPathImgFtp(), id + ".png", swapStream);
        } catch (Exception e) {
            e.printStackTrace();
            return error("create error");
        }
        JSONObject object = new JSONObject();
        object.put("ftpName", "");
        object.put("url", ftpCatalog.getFullPathImgFtp() + id + ".png");
        return success(object);
    }

    @GetMapping("/download/{id}")
    public String classify(
            @PathVariable("id") String id,
            HttpServletResponse response
    ) {
        String fileUrl = profile + "/" + id + ".png";
        if (fileUrl != null) {
            File file = new File(fileUrl);
            if (file.exists()) {
                response.setContentType("application/force-download");
                response.setHeader("Content-Disposition", "attachment;fileName=" + id + ".png");
                byte[] buffer = new byte[1024];
                FileInputStream inputStream = null;
                BufferedInputStream bufferedInputStream = null;
                try {
                    inputStream = new FileInputStream(file);
                    bufferedInputStream = new BufferedInputStream(inputStream);
                    OutputStream os = response.getOutputStream();
                    int i = bufferedInputStream.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bufferedInputStream.read(buffer);
                    }
                    System.out.println("success");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (inputStream != null) {
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return null;
    }
}
